<?php
require_once 'readmains_controller.php';
class DocgiasController extends AppController {

	var $name = 'Docgias';
    var $helpers = array('Ajax', 'Javascript', 'Html', 'Form','DatePicker');
    var $components = array('FileUpload.FileUpload');
    var $uses = array('Docgia','Thuoclop','Lop','Khoahoc','Nganh');
	function index() {
		$this->Docgia->recursive = 0;
		$this->set('docgias', $this->paginate());
	}

	function view($id = null) {
		if (!$id) {
			$this->Session->setFlash(__('Invalid docgia', true));
			$this->redirect(array('action' => 'index'));
		}
		$this->set('docgia', $this->Docgia->read(null, $id));
	}

	function add() {
	   
		if (!empty($this->data)) {
			$this->Docgia->create();
			if ($this->Docgia->save($this->data)) {
				$this->Session->setFlash(__('Độc giả đã được lưu', true));
				$this->redirect(array('action' => 'index'));
			} else {
				$this->Session->setFlash(__('Độc giả không thể lưu. Vui lòng thử lại!', true));
			}
		}
		$loaidocgias = $this->Docgia->Loaidocgia->find('list',array('fields'=>'tenloai'));
		$this->set(compact('loaidocgias'));
  
	}

	function edit($id = null) {
		if (!$id && empty($this->data)) {
			$this->Session->setFlash(__('Invalid docgia', true));
			$this->redirect(array('action' => 'index'));
		}
		if (!empty($this->data)) {
			if ($this->Docgia->save($this->data)) {
				$this->Session->setFlash(__('Độc giả đã được lưu', true));
				$this->redirect(array('action' => 'index'));
			} else {
				$this->Session->setFlash(__('Độc giả không thể lưu. Vui lòng thử lại!', true));
			}
		}
		if (empty($this->data)) {
			$this->data = $this->Docgia->read(null, $id);
		}
		$loaidocgias = $this->Docgia->Loaidocgia->find('list');
		$this->set(compact('loaidocgias'));
	}

	function delete($id = null) {
		if (!$id) {
			$this->Session->setFlash(__('Invalid id for docgia', true));
			$this->redirect(array('action'=>'index'));
		}
		if ($this->Docgia->delete($id)) {
			$this->Session->setFlash(__('Docgia deleted', true));
			$this->redirect(array('action'=>'index'));
		}
		$this->Session->setFlash(__('Docgia was not deleted', true));
		$this->redirect(array('action' => 'index'));
	}

	function upload()
	{
		if(!empty($this->data))
		{
			
			$er=$this->FileUpload->showErrors();
			if($this->FileUpload->success||empty($er))
			{
				
				$err = $this->__impTodb(WWW_ROOT.DS.'files'.DS.$this->data['Docgia']['file']['name']);
				if($err)
					$this->redirect(array('action'=>'index'),'Lỗi trong khi import');
				else
					$this->redirect(array('action'=>'index'),'Import Thành Công');
				@unlink(WWW_ROOT.DS.'files'.DS.$this->data['Docgia']['file']['name']);
			}
		 else{
                $this->Session->setFlash($er);
            }
		}    
           
	}

	
	/**
     * __impTodb($newfilename, $client_filename)
     * 
     * Hàm này đọc dữ liệu từ 1 file excel (read content of excel file)
     * Lưu trữ dữ liệu đọc được vào csdl, lưu theo từng dòng trên excel (save to DB, save each row)
     *  
     * @param mixed $newfilename đường dẫn đến file excel trên server (the patch of excel on server)
     * @param mixed $client_filename tên của file excel lúc tải lên (old filename before upload)
     *          
     * @return number (==0 if succeed, otherwise there are 7 error cases)
     * 
     */ 
   function __impTodb($filename)
   {
   		$err=0;
   		set_time_limit(300);
        //doc du lieu tu tap tin tren server
        $data = new Spreadsheet_Excel_Reader($filename,true,'UTF-8');
        $lops = array();
        //doc sheet lop
        $lops=$data->dump(true,true,0);
        $khoas = array();
        $nganhs = array();
        $this->Khoahoc->displayField='khoahoc';
        $khoahocdacos =  $this->Khoahoc->find('list');
        $this->Nganh->displayField='tennganh';
        $nganhdacos = $this->Nganh->find('list');
        foreach($lops as $lop)
        {
        	if(!in_array($lop[2],$nganhdacos))
        		if(!in_array($lop[2], $nganhs))
        			$nganhs[] =$lop[2];
        	if(!in_array($lop[3],$khoahocdacos))
        		if(!in_array($lop[3], $khoas))
        			$khoas[] =$lop[3];
       }
       /// them nganh va khoa hoc 
       $this->Khoahoc->create();
       foreach ($khoas as $khoa)
       {
       		$recordkh['Khoahoc']['khoahoc'] = $khoa;
       		if(!$this->Khoahoc->saveAll($recordkh))
       			$err=1;
       }
   		$this->Nganh->create();
       foreach ($nganhs as $nganh)
       {
       		$recordng['Nganh']['tennganh'] = $nganh;
       		if(!$this->Nganh->saveAll($recordng))
       			$err=1;
       }
       
       ///
        $khoahocdacos =  $this->Khoahoc->find('list',array('fields'=>array('khoahoc','id')));
        $nganhdacos = $this->Nganh->find('list',array('fields'=>array('tennganh','id')));
        if(!empty($khoahocdacos)&&!empty($nganhdacos))
        {
	        $this->Lop->create();
	        foreach ($lops as $lop)
	        {
	        	$lopt = $this->Lop->find('list',array('conditions'=>array('malop'=>$lop[4])));
	        	if(empty($lopt))
	        	{
		        	$recordlop['Lop']['malop']=$lop[4];
		        	$recordlop['Lop']['tenlop']=$lop[5];
		        	$recordlop['Lop']['khoahoc_id']=$khoahocdacos[$lop[3]];
		        	$recordlop['Lop']['nganh_id']=$nganhdacos[$lop[2]];
		        	if(!$this->Lop->saveAll($recordlop))
		        		$err =1;
	        	}
	        }
        }
        
        $lopdangcos = $this->Lop->find('list',array('fields'=>array('malop','id')));
        $sinhviens=$data->dump(true,true,1);
        $this->Docgia->create();
        $this->Thuoclop->create();
        foreach ($sinhviens as $sinhvien)
        {
        	if(isset($lopdangcos[$sinhvien[2]]))
        	{
        		$dg = $this->Docgia->find('list',array('conditions'=>array('maso'=>$sinhvien[3])));
        		if(empty($dg))
        		{
		        	$recorddg['Docgia']['maso']=$sinhvien[3];
		        	$recorddg['Docgia']['tennv']=$sinhvien[4];
		        	$recorddg['Docgia']['phainv']=$sinhvien[6];
		        	$recorddg['Docgia']['ngaysinh']=$sinhvien[5];
		        	$recorddg['Docgia']['ngaycap']=date('Y-m-d');
		        	$recorddg['Docgia']['email']=$sinhvien[7];
		        	$recorddg['Docgia']['loaidocgia_id']=1;
		        	if($this->Docgia->saveAll($recorddg))
		        	{
			        	$recordtl['Thuoclop']['docgia_id'] = $this->Docgia->id;
			        	$recordtl['Thuoclop']['lop_id'] =$lopdangcos[$sinhvien[2]];
			        	if(!$this->Thuoclop->saveAll($recordtl))
			        		$err = 1;
		        	}else $err=1;
        		}
        	}
        }
        return $err;
   }
}
?>
